﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClientAppraise.ViewModels.Validator
{
    public sealed class ServerErrorAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            if (validationContext.ObjectInstance is not MyObservableValidator)
            {
                return ValidationResult.Success;
            }

            var instance = (MyObservableValidator)validationContext.ObjectInstance;

            if (instance.ServerErrors == default || instance.ServerErrors.Count < 1)
            {
                return ValidationResult.Success;
            }

     

            if (!instance.ServerErrors.TryGetValue(validationContext.MemberName??"", out List<string>? errValues) || errValues == default || errValues.Count < 1)
            {
                return ValidationResult.Success;
            }

            instance.ServerErrors.Remove(validationContext.MemberName ?? "");

            return new(errValues[0]);
        }
    }

}
